package com.example.mysongplayer;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class Music_List extends AppCompatActivity {
    private List<Song> list=new ArrayList<Song>();
    private Intent intent=null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.music_list);

        //检查当前权限（若没有该权限，值为-1；若有该权限，值为0）
        int hasReadExternalStoragePermission = ContextCompat.checkSelfPermission(getApplication(),Manifest.permission.READ_EXTERNAL_STORAGE);
        Log.e("PERMISION_CODE",hasReadExternalStoragePermission+"***");
        if(hasReadExternalStoragePermission== PackageManager.PERMISSION_GRANTED){
            list = pick();
            if(list.isEmpty()){
                Log.i("tt","list is empty");
            }
            else{
                Log.i("tt","list is not empty");
            }
            init();
        }else{
            //若没有授权，会弹出一个对话框（这个对话框是系统的，开发者不能自己定制），用户选择是否授权应用使用系统权限
            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},1);
        }

    }

    //动态申请权限
    //用户选择是否同意授权后，会回调这个方法
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if(requestCode==1){
            if(permissions[0].equals(Manifest.permission.READ_EXTERNAL_STORAGE)&&grantResults[0]== PackageManager.PERMISSION_GRANTED){
                //用户同意授权，执行读取文件的代码
                list = pick();
                if(list.isEmpty()){//打印日志
                    Log.i("tt","list is empty");
                }
                else{
                    Log.i("tt","list is not empty");
                }
                init();
            }else{
                //若用户不同意授权，直接暴力退出应用。
                finish();
            }
        }
    }

    private void init(){
        SongAdapter songAdapter=new SongAdapter(
                Music_List.this,R.layout.music_item,list
        );

        List<String> data=new ArrayList<String>();
        Iterator<Song> iterator=list.iterator();
        while (iterator.hasNext()){
            Song song=(Song) iterator.next();
            data.add(song.getName()+"-"+song.getSinger());
        }
        if(data.isEmpty()){//打印日志
            Log.i("tt","list is empty");
        }
        else{
            Log.i("tt","list is not empty");
        }
        ArrayAdapter<String> arrayAdapter=new ArrayAdapter<String>(
                Music_List.this,android.R.layout.simple_expandable_list_item_1,data
        );
        ListView listView=(ListView)findViewById(R.id.List_song);
        listView.setAdapter(songAdapter);
        //点击音乐跳转到播放界面
       listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Song song = list.get(position);
                Log.i("tt", song.getName());
                Log.i("tt", song.getPath());
                //跳转到播放界面
                if (intent == null) {
                    intent = new Intent(Music_List.this, MusicActivity.class);
                    intent.putExtra("path", song.getPath());
                    intent.putExtra("song_name", song.getName());
                    intent.putExtra("singer", song.getSinger());
                    finish();
                    startActivity(intent);
                } else {
                    Toast.makeText(Music_List.this,"还有歌曲在播放",Toast.LENGTH_SHORT);
                }
            }
        });
    }



    private List<Song> pick(){
        List<Song> list=new ArrayList<Song>();
        Song song=null;
        //创建一个LocalMusicUtils来获取我们设备本地的音乐
        //通过getContentResolver()获取到contentPervider的cursor对象
        Cursor cursor= getApplicationContext().getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                null,null,null, MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
        //放到list中去
        if(cursor!=null){
            while (cursor.moveToNext()){
                song=new Song();
                //获取名字等信息
                String name=cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME));
                String singer=cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
                String path=cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
                int duration=cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION));
                long size=cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.SIZE));
                long albumid=cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID));
                long id=cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID));
                //有的时候名字和歌手会放在一起
                if(name.contains("-")){
                    String[] str=name.split("-");
                    singer=str[0];
                    name=str[1];
                }

                //把它放入song中
                song.setName(name);
                song.setSinger(singer);
                song.setPath(path);
                song.setDuration(duration);
                song.setSize(size);
                song.setAlbumId(albumid);
                song.setId(id);

                //把建好的歌曲信息放入list中
                //除去Unknown的作者
                if(!singer.contains("unknown")) {
                    list.add(song);
                }
            }
        }
        cursor.close();
        return list;
    }


}